from django.shortcuts import render, reverse, redirect, HttpResponse
from web.forms.issues import ShowProblem, issuesRecord
from django.http import JsonResponse
import datetime
from scripts.init_price_police import S28
import math
import time, datetime

labei_str = ['主题', '内容','问题类型', '模块', '状态', '派遣', '跟踪', '开始时间', '结束时间', '是否公开', '父问题']
# 用户进入主页 前端发过来数据 进行查询 在issues_record视图调用了我
def init_datas(issues_id):
    problem_reply_tuple = S28().search('problem_reply', {"problem_id": issues_id})
    data_list = []
    for i in problem_reply_tuple:
        data = {
            'id': i[0],
            'content_problem': i[1],
            'replp_type': i[2],
            'creater_user_id': i[3],
            'father_reply': i[4],
            'problem_id': i[5],
            'user_name': S28().search('user_information', {'id': i[3]})[0][1]
        }
        data_list.append(data)
    return data_list

# 对返回来的get参数进入sql处理
def py_str(requested):
    ret = ''
    keys = []
    for i in requested:
        keys.append(i)
    for i in requested:
        if i != 'page':
            for j in requested[i]:
                if len(requested[i]) == 1:
                    if i == keys[len(keys)-1]:
                        ret += i + '=' + '"' +str(j)+'"'+ ' '
                    else:
                        ret += i + '=' + '"' +str(j)+'"' + ' and '
                else:
                    if j != requested[i][len(requested[i])-1]: # 2 = len(ret[i]-1)
                        ret += i + '=' + '"' +str(j)+'"' + ' or '
                    else:
                        if i == keys[len(keys)-1]:
                            ret += i + '=' + '"' +str(j)+'"'+ ' '
                        else:
                            ret += i + '=' + '"' +str(j)+'"' + ' and '

    return ret
# 给前端返回的正则字符串
def re_paramter(a):
    re = ''
    for i in a :
        for j in a[i]:
            re += str('&'+''+i + '=' + str(j))
    return re


def issues(request, project_id):
    """问题页面展示"""

    issues_project_id = 'where project_id={}'.format(project_id)  # 给项目做条件  sql语句加条件 如果没有进入这个项目就不会显示这个项目的信息
    new_dict = {}  # 给sql处理函数构造字典
    for i in request.GET:  # 循环给 new_dict 添加数据
        new_dict[i] = request.GET.getlist(i)
    # 这个参数是sql语句  是sql处理函数的返回值
    py_ret = py_str(new_dict)
    # 这个参数是给前端传的正则的字符串
    re_str = re_paramter(new_dict)
    if len(py_ret) !=0:
        py_ret = 'where'+ ' ' + py_ret
        issues_project_id = ' and project_id="{}"'.format(project_id)
    if request.method == "GET":
        lim = 0  # 定义了一个变量 他将要控制 sql 的分页limit
        if request.GET.get('page'):  # 检测是否有 page蚕食  page参数就是分页
            if request.GET.get('page').isdecimal():  # 如果这个参数是一个十进制的字符串类型的变量
                if int(request.GET.get('page')) >=1:
                    lim = int(request.GET.get('page'))-1
        form = ShowProblem(requested=project_id)
        problem = S28().py_searche('select * from problem as p left join\n'
                                   ' user_information as u on p.assign_user_information=u.id left join user_information as us on\n'
                                   ' p.follow_user_information=us.id  {}{} limit {},2'.format(py_ret,issues_project_id,lim*2))
        problem_count = S28().py_searche('select count(p.id) from problem as p left join user_information as u on p.assign_user_information=u.id '
                                         'left join user_information as us on p.follow_user_information=us.id {}'.format(py_ret))[0][0]
        problem_list = []
        for i in range(math.ceil(problem_count/2)):
            problem_list.append(i+1)
        # 派遣的input框选择


        return render(request, 'issues.html', {'form': form, 'problem': problem, 'problem_list': problem_list, 'lim': lim+1, 're_str':re_str})
    # 新建问题的form表单验证  通过就写入数据库
    form = ShowProblem(requested=project_id, data=request.POST)
    if form.is_valid():
        ret = {'project_id': project_id}
        for i,j in request.POST.items():
            if i != 'csrfmiddlewaretoken':
                ret[i] = j
        S28().insert_into('problem', ret)
        return JsonResponse({'status': True, 'data':ret})
    return JsonResponse({'status': False, 'error':form.errors})


# 显示detial左侧问题的详细的信息
def issues_detail(request, project_id, issues_id):
    """编辑问题"""
    ret = S28().py_searche('select the_title,'
                           'the_content,'
                           'problem_type,'
                           'modular,'
                           'statused,'
                           'assign_user_information,'
                           'follow_user_information,'
                           'start_time,end_time,'
                           'pattern,'
                           'parent_problem from problem where id="{}"'.format(issues_id))[0]
    form = ShowProblem(requested=project_id, val=ret)
    return render(request, 'issues_detail.html', {'form':form, 'issues_id': issues_id})

# 显示
def issues_record(request, project_id, issues_id):
    """初始化操作记录"""

    if request.method == 'GET':
        problem_reply_tuple = S28().search('problem_reply', {"problem_id": issues_id})
        data_list = []
        ret = init_datas(issues_id)
        return JsonResponse({'status': True ,'data':ret})
    form = issuesRecord(data=request.POST)
    if form.is_valid():
        #数据库添加
        content = form.cleaned_data.get('content')
        father_id = form.cleaned_data.get('father_id')
        replp_type = '修改记录'
        if content != 0:
            replp_type = '回复'
        S28().insert_into('problem_reply', {'content_problem':content, 'replp_type':replp_type, 'creater_user_id':request.user_id, 'father_reply':father_id,'problem_id':issues_id})
        ret = init_datas(issues_id)

        return JsonResponse({'status':True, 'data': ret})
    return JsonResponse({'status':False, 'error':form.errors})

def issues_update(request, project_id, issues_id):
    form = ShowProblem(requested=project_id, data=request.POST)
    rett = S28().py_searche(
        'select the_title,the_content, problem_type, modular,statused,assign_user_information,follow_user_information,start_time,end_time,pattern,parent_problem from problem where id="{}"'.format(
            issues_id))[0]
    # 这个是渲染的修改记录
    update_str = ''
    if form.is_valid():
        ret = {}
        num = 0
        for i, j in request.POST.items():
            if i != 'csrfmiddlewaretoken':
                ret[i] = j
                if num == 7 or num == 8:
                    if str(rett[num]) != str(request.POST.get(i)):
                        update_str += '  '+str(labei_str[num])+'从: ['+str(rett[num])+'] 变更为：['+request.POST.get(i)+']'
                else:
                    if str(rett[num]) != str(j):
                        update_str += '  ' + str(labei_str[num]) + '从: [' + str(rett[num]) + '] 变更为：[' + str(j) + ']'
                num += 1
        S28().upload('problem', ret, {'id': issues_id})
        S28().insert_into('problem_reply', {'content_problem':update_str, 'replp_type':'修改记录', 'creater_user_id': request.user_id, 'father_reply':'0', 'problem_id':issues_id})
        return JsonResponse({'status': True, 'data': ret})
    return JsonResponse({'status': False, 'error': form.errors})
